package cn.b.sky.message.controller;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.enums.ParameterEnums;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.common.utils.DateUtils;
import cn.b.sky.message.enums.MessageRecevierType;
import cn.b.sky.message.model.InstantMessageInfo;
import cn.b.sky.message.model.MessageConfigInfo;
import cn.b.sky.message.model.MessageContentInfo;
import cn.b.sky.message.model.MessageReceiverInfo;
import cn.b.sky.message.model.condition.InstantMessageCondition;
import cn.b.sky.message.model.condition.MessageConfigCondition;
import cn.b.sky.message.service.MessageService;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.user.service.ParameterService;
import cn.b.sky.user.service.model.ParameterEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * <strong>Title : MessageController.java<br>
 * </strong> <strong>Package : cn.b.sky.user.controller<br>
 * </strong> <strong>Description : </strong> 消息控制器<br>
 * <strong>Create on : 2015-9-9 下午05:27:59<br>
 * </strong>
 * <p>
 * 
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 *          <strong>修改历史:</strong><br>
 *          修改人 | 修改日期 | 修改描述<br>
 *          -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping(value = "/message/*")
public class MessageController extends SecurityController {
  @Resource
  MessageService messageService;

  @Resource
  ParameterService parameterService;

  @RequestMapping("/getMessage")
  @ResponseBody
  public DWZResult getMessage(int count, int time, HttpServletResponse response) throws InterruptedException {
    int t = 0;// 计算超时时间（秒）
    int interval = 10;// 查询间隔
    ParameterEntity parameter = parameterService.getParameterEntityByCode(ParameterEnums.MESSAGERRESHTIME.getCode(), this.getSiteCode());
    if (parameter != null && !StringUtils.isEmpty(parameter.getDefaultValue())) {
      interval = Integer.parseInt(parameter.getDefaultValue());
    }
    int mcount = 0;// 消息数量
    // 循环次数由最大等待时间及数据变化有无变化决定
    while (t <= time) {
      t += interval;
      mcount = messageService.selectUnReadMessageCount(this.getSiteCode(), SecurityContextUtil.getCurrentUserName());
      if (mcount != count) {
        break; // 未读消息数量变化时跳出循环
      } else if (t <= time) {
        Thread.sleep(interval * 1000);
      }
    }
    return ajaxDone(mcount);
  }

  @RequestMapping("messageList")
  public String messageList(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    int count = messageService.selectUnReadMessageCount(SecurityContextUtil.getSiteCode(),
        SecurityContextUtil.getCurrentUserName());
    String unreadCount = "";
    if (count != 0) {
      unreadCount = Integer.toString(count);
    }
    model.addAttribute("unreadCount", unreadCount);
    return "message/message_list";
  }

  @RequestMapping("unReadMessage")
  public String unReadMessage(Model model, @ModelAttribute("condition") InstantMessageCondition message,
                              String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    message.setUserCode(SecurityContextUtil.getCurrentUserName());
    message.setSiteCode(SecurityContextUtil.getSiteCode());
    if (StringUtils.isEmpty(message.getOrderField())) {
      message.setOrderField("receivedTime");
    }
    List<InstantMessageInfo> logs = messageService.selectUnReadMeaage(message);
    int count = messageService.selectUnReadMessageCount(SecurityContextUtil.getSiteCode(), message.getUserCode());
    message.setData(logs);
    message.setTotalCount(count);
    model.addAttribute("page", message);
    return "message/unread_message";
  }

  @RequestMapping("viewMessage")
  public String viewMessage(Model model, String navTabId, String id) {
    InstantMessageInfo message = messageService.selectInstantMessageById(Long.parseLong(id));
    model.addAttribute("message", message);
    model.addAttribute(NAVTABID, navTabId);
    messageService.doMarkAsRead(Long.parseLong(id));
    return "message/message_view";

  }

  @RequestMapping("viewhisMessage")
  public String viewhisMessage(Model model, String navTabId, String id) {
    InstantMessageInfo message = messageService.selectInstantMessageById(Long.parseLong(id));
    model.addAttribute("message", message);
    model.addAttribute(NAVTABID, navTabId);
    return "message/message_his_view";
  }

  @RequestMapping("hisMessage")
  public String hisMessage(Model model, @ModelAttribute("condition") InstantMessageCondition message, String navTabId)
      throws ParseException {
    model.addAttribute(NAVTABID, navTabId);
    message.setUserCode(SecurityContextUtil.getCurrentUserName());
    message.setSiteCode(SecurityContextUtil.getSiteCode());
    if (!StringUtils.isEmpty(message.getFromTimeStr())) {
      message.setFromTime(DateUtils.getDateUtils().getDateFromStr(message.getFromTimeStr() + " 00:00:00"));
    } else {
      message.setFromTime(null);
    }
    if (!StringUtils.isEmpty(message.getToTimeStr())) {
      message.setToTime(DateUtils.getDateUtils().getDateFromStr(message.getToTimeStr() + " 23:59:59"));
    } else {
      message.setToTime(null);
    }
    if (StringUtils.isEmpty(message.getOrderField())) {
      message.setOrderField("receivedTime");
    }
    List<InstantMessageInfo> logs = messageService.selectHisInstantMessageList(message);
    int count = messageService.selectHisInstantMessageCount(message);
    message.setData(logs);
    message.setTotalCount(count);
    model.addAttribute("page", message);
    return "message/his_message";
  }

  @RequestMapping("messageConfig")
  public String messageConfig(Model model, @ModelAttribute("condition") MessageConfigCondition message,
                              String navTabId) {

    model.addAttribute(NAVTABID, navTabId);
    message.setSiteCode(SecurityContextUtil.getSiteCode());
    List<MessageConfigInfo> messages = messageService.selectMessageConfigList(message);
    int count = messageService.selectMessageConfigCount(message);
    message.setData(messages);
    message.setTotalCount(count);
    model.addAttribute("page", message);
    return "message/message_config_list";

  }
  
  /**
   * 
   * <strong>Title : messageConfigLookUp<br></strong>
   * <strong>Description : </strong>消息配置查找带回<br> 
   * <strong>Create on : 2016年10月19日 上午9:51:56<br></strong>
   * <p>
   * @param model
   * @param message
   * @param navTabId
   * @return
   * String
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("messageConfigLookUp")
  public String messageConfigLookUp(Model model, @ModelAttribute("condition") MessageConfigCondition message,
                                    String navTabId) {

    model.addAttribute(NAVTABID, navTabId);
    message.setSiteCode(SecurityContextUtil.getSiteCode());
    List<MessageConfigInfo> messages = messageService.selectMessageConfigList(message);
    int count = messageService.selectMessageConfigCount(message);
    message.setData(messages);
    message.setTotalCount(count);
    model.addAttribute("page", message);
    return "message/message_config_lookup";

  }

  @RequestMapping("validateMessageCode")
  @ResponseBody
  public boolean validateMessageCode(String messageCode, Model model) {
    if (!StringUtils.isEmpty(messageCode)) {
      return null == messageService.selectMessageConfig(SecurityContextUtil.getSiteCode(), messageCode);
    }
    return true;

  }

  @RequestMapping("addMessage")
  public String addMessage(Model model, String navTabId) {
    List<MessageContentInfo> contents = messageService.selectAllLanguage();
    model.addAttribute("contents", contents);
    model.addAttribute(NAVTABID, navTabId);
    return "message/message_config_add";
  }

  @RequestMapping("editMessage")
  public String editMessage(Model model, String navTabId, String id) {

    MessageConfigInfo message = messageService.selectMessageConfig(SecurityContextUtil.getSiteCode(), id);
    List<MessageReceiverInfo> receivers = messageService.selectMessageReceiver(SecurityContextUtil.getSiteCode(), id);
    String receiverUser = "";
    String receiverRole = "";
    String receiverOrg = "";
    String receiverUserName = "";
    String receiverRoleName = "";
    String receiverOrgName = "";
    if (receivers != null) {
      for (MessageReceiverInfo rinfo : receivers) {
        if (rinfo.getReceiverType().equals(MessageRecevierType.USER.getValue())) {
          receiverUser += rinfo.getReceiverCode() + ",";
          receiverUserName += rinfo.getReceiverName() + ",";
        } else if (rinfo.getReceiverType().equals(MessageRecevierType.ROLE.getValue())) {
          receiverRole += rinfo.getReceiverCode() + ",";
          receiverRoleName += rinfo.getReceiverName() + ",";
        } else if (rinfo.getReceiverType().equals(MessageRecevierType.ORGANIZATION.getValue())) {
          receiverOrg += rinfo.getReceiverCode() + ",";
          receiverOrgName += rinfo.getReceiverName() + ",";
        }
      }
      if (!StringUtils.isEmpty(receiverUser)) {
        receiverUser = receiverUser.substring(0, receiverUser.length() - 1);
        message.setReceiverUser(receiverUser);
      }
      if (!StringUtils.isEmpty(receiverRole)) {
        receiverRole = receiverRole.substring(0, receiverRole.length() - 1);
        message.setReceiverRole(receiverRole);
      }
      if (!StringUtils.isEmpty(receiverOrg)) {
        receiverOrg = receiverOrg.substring(0, receiverOrg.length() - 1);
        message.setReceiverOrg(receiverOrg);
      }
      if (!StringUtils.isEmpty(receiverUserName)) {
        receiverUserName = receiverUserName.substring(0, receiverUserName.length() - 1);
        message.setReceiverUserName(receiverUserName);
      }
      if (!StringUtils.isEmpty(receiverRoleName)) {
        receiverRoleName = receiverRoleName.substring(0, receiverRoleName.length() - 1);
        message.setReceiverRoleName(receiverRoleName);
      }
      if (!StringUtils.isEmpty(receiverOrgName)) {
        receiverOrgName = receiverOrgName.substring(0, receiverOrgName.length() - 1);
        message.setReceiverOrgName(receiverOrgName);
      }
    }
    List<MessageContentInfo> contents = messageService.selectContentListByMessageCode(SecurityContextUtil.getSiteCode(),
        id);
    model.addAttribute("message", message);
    model.addAttribute("contents", contents);
    model.addAttribute(NAVTABID, navTabId);
    return "message/message_config_add";

  }

  @RequestMapping("viewMessageConfig")
  public String viewMessageConfig(Model model, String navTabId, String id) {
    MessageConfigInfo message = messageService.selectMessageConfig(SecurityContextUtil.getSiteCode(), id);
    List<MessageReceiverInfo> receivers = messageService.selectMessageReceiver(SecurityContextUtil.getSiteCode(), id);
    String receiverUser = "";
    String receiverRole = "";
    String receiverOrg = "";
    String receiverUserName = "";
    String receiverRoleName = "";
    String receiverOrgName = "";
    if (receivers != null) {
      for (MessageReceiverInfo rinfo : receivers) {
        if (rinfo.getReceiverType().equals(MessageRecevierType.USER.getValue())) {
          receiverUser += rinfo.getReceiverCode() + ",";
          receiverUserName += rinfo.getReceiverName() + ",";
        } else if (rinfo.getReceiverType().equals(MessageRecevierType.ROLE.getValue())) {
          receiverRole += rinfo.getReceiverCode() + ",";
          receiverRoleName += rinfo.getReceiverName() + ",";
        } else if (rinfo.getReceiverType().equals(MessageRecevierType.ORGANIZATION.getValue())) {
          receiverOrg += rinfo.getReceiverCode() + ",";
          receiverOrgName += rinfo.getReceiverName() + ",";
        }
      }
      if (!StringUtils.isEmpty(receiverUser)) {
        receiverUser = receiverUser.substring(0, receiverUser.length() - 1);
        message.setReceiverUser(receiverUser);
      }
      if (!StringUtils.isEmpty(receiverRole)) {
        receiverRole = receiverRole.substring(0, receiverRole.length() - 1);
        message.setReceiverRole(receiverRole);
      }
      if (!StringUtils.isEmpty(receiverOrg)) {
        receiverOrg = receiverOrg.substring(0, receiverOrg.length() - 1);
        message.setReceiverOrg(receiverOrg);
      }
      if (!StringUtils.isEmpty(receiverUserName)) {
        receiverUserName = receiverUserName.substring(0, receiverUserName.length() - 1);
        message.setReceiverUserName(receiverUserName);
      }
      if (!StringUtils.isEmpty(receiverRoleName)) {
        receiverRoleName = receiverRoleName.substring(0, receiverRoleName.length() - 1);
        message.setReceiverRoleName(receiverRoleName);
      }
      if (!StringUtils.isEmpty(receiverOrgName)) {
        receiverOrgName = receiverOrgName.substring(0, receiverOrgName.length() - 1);
        message.setReceiverOrgName(receiverOrgName);
      }
    }
    List<MessageContentInfo> contents = messageService.selectContentListByMessageCode(SecurityContextUtil.getSiteCode(),
        id);
    model.addAttribute("message", message);
    model.addAttribute("contents", contents);
    model.addAttribute(NAVTABID, navTabId);
    return "message/message_config_view";
  }

  @RequestMapping("saveMessage")
  @ResponseBody
  public DWZResult saveMessage(Model model, String navTabId, String id, MessageConfigInfo message,
                               HttpServletRequest request) {
    if (message == null) {

      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    List<MessageContentInfo> contents = messageService.selectAllLanguage();
    // 处理消息内容
    String[] contentArry = message.getMessageContents().split("\\[&]");
    List<MessageContentInfo> contentList = new ArrayList<MessageContentInfo>();
    for (int i = 0; i < contentArry.length; i++) {
      String c = contentArry[i];
      if (!StringUtils.isEmpty(c.trim())) {
        MessageContentInfo cinfo = new MessageContentInfo();
        cinfo.setSiteCode(SecurityContextUtil.getSiteCode());
        cinfo.setMessageCode(message.getMessageCode());
        cinfo.setLanguageCode(contents.get(i).getLanguageCode());
        cinfo.setMessageContent(c);
        contentList.add(cinfo);
      }
    }
    message.setContents(contentList);
    // 处理发送方式
    if (message.getInstantMessageFlag() == null) {
      message.setInstantMessageFlag(0);
    }
    if (message.getEmailMessageFlag() == null) {
      message.setEmailMessageFlag(0);
    }
    if (message.getShortMessageFlag() == null) {
      message.setShortMessageFlag(0);
    }
    if (message.getWechatMessageFlag() == null) {
      message.setWechatMessageFlag(0);
    }
    if (message.getSmartWatchMessageFlag() == null) {
      message.setSmartWatchMessageFlag(0);
    }
    // 处理接收人
    List<MessageReceiverInfo> receivers = new ArrayList<MessageReceiverInfo>();
    if (!StringUtils.isEmpty(message.getReceiverUser())) {
      String[] receiverUser = message.getReceiverUser().split(",");
      for (String user : receiverUser) {
        MessageReceiverInfo rinfo = new MessageReceiverInfo();
        rinfo.setSiteCode(SecurityContextUtil.getSiteCode());
        rinfo.setMessageCode(message.getMessageCode());
        rinfo.setReceiverCode(user);
        rinfo.setReceiverType(MessageRecevierType.USER.getValue());
        receivers.add(rinfo);
      }
    }

    if (!StringUtils.isEmpty(message.getReceiverOrg())) {
      String[] receiverOrg = message.getReceiverOrg().split(",");
      for (String o : receiverOrg) {
        MessageReceiverInfo rinfo = new MessageReceiverInfo();
        rinfo.setSiteCode(SecurityContextUtil.getSiteCode());
        rinfo.setMessageCode(message.getMessageCode());
        rinfo.setReceiverCode(o);
        rinfo.setReceiverType(MessageRecevierType.ORGANIZATION.getValue());
        receivers.add(rinfo);
      }
    }

    if (!StringUtils.isEmpty(message.getReceiverRole())) {
      String[] receiverRole = message.getReceiverRole().split(",");
      for (String r : receiverRole) {
        MessageReceiverInfo rinfo = new MessageReceiverInfo();
        rinfo.setSiteCode(SecurityContextUtil.getSiteCode());
        rinfo.setMessageCode(message.getMessageCode());
        rinfo.setReceiverCode(r);
        rinfo.setReceiverType(MessageRecevierType.ROLE.getValue());
        receivers.add(rinfo);
      }
    }
    message.setReceivers(receivers);
    setCreateInfo(message);
    message.setSiteCode(SecurityContextUtil.getSiteCode());
    if (StringUtils.isEmpty(id)) {
      messageService.insertMessageConfig(message);
      return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), null, null, null, null);
    } else {
      messageService.updateMessageConfig(message);
      return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), null, null, null, null);
    }

  }

  @RequestMapping("deleteMessage")
  @ResponseBody
  public DWZResult deleteMessage(Model model, String navTabId, String id, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    String[] messages = ids.split(",");
    for (String m : messages) {
      messageService.deleteMessageConfig(SecurityContextUtil.getSiteCode(), m);
    }
    return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);

  }

  @RequestMapping("testMessage")
  public String testMessage(Model model, String navTabId, String id) {

    MessageConfigInfo message = new MessageConfigInfo();
    message.setMessageCode(id);
    model.addAttribute("message", message);
    model.addAttribute(NAVTABID, navTabId);
    return "message/message_test";

  }

  @RequestMapping("sendMessage")
  @ResponseBody
  public DWZResult sendMessage(Model model, String navTabId, MessageConfigInfo message, HttpServletRequest request) {
    if (message == null) {

      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String[] paramrters = null;
    if (!StringUtils.isEmpty(message.getParamrters())) {
      paramrters = message.getParamrters().split(",");
    }
    messageService.sendMessage(SecurityContextUtil.getSiteCode(), message.getMessageCode(), paramrters);
    return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), null, null, null, null);

  }

}
